package com.wnhz.work.yz.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.google.gson.Gson;
import com.wnhz.work.yz.BaseActivity;
import com.wnhz.work.yz.MyApplication;
import com.wnhz.work.yz.R;
import com.wnhz.work.yz.bean.AddressBean;
import com.wnhz.work.yz.bean.Finish1;
import com.wnhz.work.yz.bean.FormListBean;
import com.wnhz.work.yz.utils.Url;
import com.wnhz.work.yz.utils.xutils3.MyCallBack;
import com.wnhz.work.yz.utils.xutils3.XUtil;
import com.wnhz.work.yz.wheel.AlertAddress;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

/**
 * ---增值税专用发票
 */
public class TaxInvoiceActivity extends BaseActivity implements View.OnClickListener {
    private TextView title;
    private TextView tv_right;
    private TextView tv_invoice_name;

    private TextView tv_texture;
    private EditText ed_head, et_company_name, et_recognition, et_bank, et_bank_account, et_address_detail, et_phone;
    private TextView et_address;
    public static AppCompatActivity mActivity;
    private TextView et_unit_address;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tax_invoice);
        mActivity = this;

        EventBus.getDefault().register(this);
     //   MyApplication.getInstance().addDestoryActivity(this, "addform3");
        initData();
        initView();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(Finish1 event) {
        finish();
    }


    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);//反注册EventBus
        super.onDestroy();
    }
    private int isUpdate;
    private FormListBean.InfoEntity info1 = new FormListBean.InfoEntity();
    private String id;

    private void initData() {
        isUpdate = getIntent().getIntExtra("isUpdate", 0);
        //
        if (isUpdate == 1) {
            id = getIntent().getStringExtra("id");
            getData();
        }

        //
    }

    private void getData() {
        Map<String, Object> map = new HashMap<>();
        map.put("token", MyApplication.getInstance().getUserBean().getToken());
        map.put("id", id);
        showDialog();
      /*  Set keys = map.keySet();
        if (keys != null) {
            Iterator iterator = keys.iterator();
            while (iterator.hasNext()) {
                Object key = iterator.next();
                Object value = map.get(key);
                Log.e("----" + key, ":" + value + "\n");
            }
        }*/
        XUtil.Post(Url.INVOICE_DETAIL, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Log.i("----", "onSuccess:= " + result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String res = jsonObject.optString("result");
                    String info = jsonObject.optString("info");
                    if ("1".equals(res)) {
                        Gson gson = new Gson();
                        info1 = gson.fromJson(info, FormListBean.InfoEntity.class);
                    } else {
                        if ("-1".equals(res)) {
                            info = "请重新登录";
                        }
                        MyToast(info);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                closeDialog();
                initView();
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                closeDialog();
            }
        });


    }

    private View include_address, include_noAddress;
    private TextView tv_name, tv_phone, tv_address, tv_company_name;

    private void initView() {
        /**
         * 判断是否有地址选择显示隐藏的布局
         */
        et_unit_address = (TextView) findViewById(R.id.et_unit_address);
        include_address = findViewById(R.id.include_choose_address);//有地址
        include_noAddress = findViewById(R.id.include_choose_noAddress);//无收货地址
        include_address.setOnClickListener(this);
        include_noAddress.setOnClickListener(this);

        include_address.setVisibility(View.GONE);// TODO  暂时设为不可见
        tv_name = (TextView) findViewById(R.id.tv_name);
        tv_phone = (TextView) findViewById(R.id.tv_phone);
        tv_address = (TextView) findViewById(R.id.tv_address);

        //
        title = (TextView) findViewById(R.id.view_main_middle_title);
        title.setText("发票");
        findViewById(R.id.btn_main_left).setOnClickListener(this);
        findViewById(R.id.submit).setVisibility(View.VISIBLE);
        findViewById(R.id.submit).setOnClickListener(this);
        tv_right = (TextView) findViewById(R.id.submit);
        tv_right.setVisibility(View.VISIBLE);
        tv_right.setText("保存");
        tv_right.setTextColor(0xff008c99);

        tv_invoice_name = (TextView) findViewById(R.id.tv_invoice_name);

        findViewById(R.id.rl_choose_type).setOnClickListener(this);//发票类型
        ed_head = (EditText) findViewById(R.id.ed_head);
        tv_texture = (TextView) findViewById(R.id.tv_texture);//发票材质
        et_company_name = (EditText) findViewById(R.id.et_company_name);//发票抬头
        et_recognition = (EditText) findViewById(R.id.et_recognition);//识别号
        et_bank = (EditText) findViewById(R.id.et_bank);//开户行
        et_bank_account = (EditText) findViewById(R.id.et_bank_account);//银行账号
        et_address = (TextView) findViewById(R.id.et_address);//公司地址
        et_address.setOnClickListener(this);
        et_address_detail = (EditText) findViewById(R.id.et_address_detail);//详细地址
        et_phone = (EditText) findViewById(R.id.et_phone);//公司电话
        if (isUpdate == 1) {
            et_company_name.setText(info1.getInvoice_company());
            ed_head.setText(info1.getInvoice_title());
            et_recognition.setText(info1.getInvoice_taxpayer_id());
            et_bank.setText(info1.getInvoice_bank());
            et_bank_account.setText(info1.getInvoice_bank_account());
            //  et_address.setText(info.getGet_province() + "-" + info.getGet_city() + "-" + info.getGet_district());
            et_address_detail.setText(info1.getInvoice_address());
            et_phone.setText(info1.getInvoice_phone());
            include_address.setVisibility(View.VISIBLE);
            include_noAddress.setVisibility(View.GONE);
            tv_name.setText(info1.getGet_consignee());
            tv_phone.setText(info1.getGet_tel());
            tv_address.setText(info1.getGet_province() + "" + info1.getGet_city() + "" + info1.getGet_district());
            receiptAddrId = info1.getAddress_id();
            et_unit_address.setText(info1.getUnit_address());
        }
    }

    private static final int CODE_ADDRESS = 111;
    private static final int CODE_INVOICE = 112;

    @Override
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()) {
            case R.id.btn_main_left:
                finish();
                break;

            //有地址，前去修改
            case R.id.include_choose_address:
                intent = new Intent(this, ChooseAddressActivity.class);
                startActivityForResult(intent, CODE_ADDRESS);
                break;

            //无地址，添加收货地址
            case R.id.include_choose_noAddress:
                intent = new Intent(this, ChooseAddressActivity.class);
                startActivityForResult(intent, CODE_ADDRESS);
                break;

            //保存
            case R.id.submit:
                String invoiceTitle = et_company_name.getText().toString();
                String taxpayerId = et_recognition.getText().toString();
                String bank = et_bank.getText().toString();
                String bankAccount = et_bank_account.getText().toString();
                String detailAddress = et_address_detail.getText().toString();
                String address = detailAddress;
                String phone = et_phone.getText().toString();
                if (!"".equals(invoiceTitle) && !"".equals(taxpayerId) && !"".equals(bank) && !"".equals(bankAccount)
                        && !"".equals(detailAddress) && !"".equals(phone)) {
//                    intent = new Intent();
//                    intent.putExtra("result", "增值税专用发票");
//                    intent.putExtra("invoiceTitle", invoiceTitle);
//                    intent.putExtra("taxpayerId", taxpayerId);
//                    intent.putExtra("bank", bank);
//                    intent.putExtra("bankAccount", bankAccount);
//                    intent.putExtra("address", address);
//                    intent.putExtra("phone", phone);
//                    intent.putExtra("type1", "3");
//                    setResult(RESULT_OK, intent);
//                    finish();
                    upLoad();
                } else if ("".equals(invoiceTitle)) {
                    MyToast("请填写公司名称");
                } else if ("".equals(taxpayerId)) {
                    MyToast("请填写识别号");
                } else if ("".equals(bank)) {
                    MyToast("请填写开户行");
                } else if ("".equals(bankAccount)) {
                    MyToast("请填写银行账号");
                } else if ("".equals(detailAddress)) {
                    MyToast("请填写详细地址");
                } else if ("".equals(phone)) {
                    MyToast("请填写公司电话");
                }
                break;

            //发票类型
            case R.id.rl_choose_type:
//                intent = new Intent(this, InvoiceTypeActivity.class);
//                intent.putExtra("from", "Tax");
//                startActivity(intent);
                break;
            case R.id.et_address:
                intent = new Intent(this, AlertAddress.class);
                startActivityForResult(intent, 115);
                overridePendingTransition(R.anim.push_up_in, R.anim.push_up_out);


                break;
            default:
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 115) {

            if (resultCode == 333) {
                if (data != null) {
                    et_address.setText(data.getStringExtra("address"));
                }
            }

        } else if (requestCode == CODE_ADDRESS) {
            //地址回调
            if (resultCode == RESULT_OK) {
                if (null != data) {
                    AddressBean addressBean = (AddressBean) data.getSerializableExtra("addressBean");
                    include_address.setVisibility(View.VISIBLE);
                    include_noAddress.setVisibility(View.GONE);
                    String province = addressBean.getProvince();
                    String city = addressBean.getCity();
                    String district = addressBean.getDistrict();
                    String place = addressBean.getPlace();
                    String addr = province + city + district + place;
                    tv_name.setText(addressBean.getConsignee());
                    tv_phone.setText(addressBean.getTelephone());
                    tv_address.setText(addr);
                    receiptAddrId = addressBean.getAddress_id();
                }
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void upLoad() {
        /**
         * Member/addInvoice()新增发票
         参数token,
         type：发票类型：1：普通，2：增值
         invoice_title：发票抬头
         invoice_company 发票公司
         invoice_taxpayer_id 纳税人识别号
         invoice_address 发票地址
         invoice_phone 发票电话
         invoice_bank 开户银行
         invoice_bank_account 开户账号
         invoice_detail 发票明细(明细、办公用品、耗材)
         get_consignee 收货人
         get_tel 电话
         get_address 地址
         get_province省
         get_city市
         get_district区
         default 1为默认，0不默认

         */

        if (ed_head.getText().toString().trim().equals("")) {
            MyToast("请填写发票抬头");
            return;
        }
        if (et_unit_address.getText().toString().trim().equals("")) {
            MyToast("请填写公司地址");
            return;
        }
        Map<String, Object> map = new HashMap<>();
        map.put("token", MyApplication.getInstance().getUserBean().getToken());
        map.put("type", 2);
        map.put("invoice_title", ed_head.getText().toString().trim());
        map.put("invoice_company", et_company_name.getText().toString().trim());
        map.put("invoice_taxpayer_id", et_recognition.getText().toString().trim());
        map.put("invoice_address", et_address_detail.getText().toString());
        //   map.put("address_id", receiptAddrId);
        map.put("invoice_phone", et_phone.getText().toString().trim());
        map.put("invoice_bank", et_bank.getText().toString());
        map.put("invoice_bank_account", et_bank_account.getText().toString());
        map.put("get_tel", et_phone.getText().toString().trim());
        map.put("unitAddress", et_unit_address.getText().toString().trim());
        map.put("detailAddress", et_address_detail.getText().toString().trim());
//        if (!str.equals(et_address_detail.getText().toString())){
//            str = str + et_address_detail.getText().toString().trim();
//        }
        //  map.put("invoice_detail", invoiceContent);
//        map.put("get_consignee", invoice_title);
        //        map.put("get_province", invoice_title);
//        if (et_address.getText().toString().equals("")) {
//            MyToast("请选择地址");
//            return;
//        }

//        String url2[] = et_address.getText().toString().split("-");
//        map.put("get_province", url2[0]);
//        map.put("get_city", url2[1]);
//        map.put("get_district", url2[2]);
//        map.put("default", invoice_title);
        String url = Url.ADDINVOICE;
        if (isUpdate == 1) {
            map.put("id", info1.getId());
            url = Url.EDITINVOICE;
        }


        showDialog();
      /*  Set keys = map.keySet();
        if (keys != null) {
            Iterator iterator = keys.iterator();
            while (iterator.hasNext()) {
                Object key = iterator.next();
                Object value = map.get(key);
                Log.e("----" + key, ":" + value + "\n");
            }
        }*/
        XUtil.Post(url, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Log.i("----", "onSuccess:= " + result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String res = jsonObject.optString("result");
                    String info = jsonObject.optString("info");
                    if ("1".equals(res)) {
                        MyToast(info);
//                        MyApplication.getInstance().destoryActivity("addform1");
                        EventBus.getDefault().post(new Finish1());
//                        MyApplication.getInstance().destoryActivity("addform2");
//                        MyApplication.getInstance().destoryActivity("addform3");
                        finish();
                    } else {
                        if ("-1".equals(res)) {
                            info = "请重新登录";
                        }
                        MyToast(info);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                closeDialog();

                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                closeDialog();
            }
        });

    }

    private String receiptAddrId;

}
